define(function(require,exports,module){
    var Backbone = require('backbone');
    var _ = require('_');
    //模板
    var areaTemp = '<div class="J_MultiMask"></div>'+
        '<div class="J_MultiAreaSel">'+
        '<div class="hd fn-clear">'+
            '<h2>请选择区域</h2>'+
            '<a href="javascript:void(0);" class="J_MultiClose" title="关闭">关闭</a>'+
        '</div>'+
        '<div class="selected-area fn-clear">'+
            '<ul class="fn-left"></ul>'+
            '<button class="J_MultiSubmit fn-right" type="button">确定</button>'+
            '<a class="J_MultiClear fn-right" href="javascript:void(0)" title="清空选择">清空选择</a>'+
        '</div>'+
        '<div class="province-list">' +
        '<p class="J_Nation fn-clear"><label><input type="checkbox" value="0"><span>全国</span></label></p>'+
        '</div>'+
    '</div>';
    //已选地区Id
    var selAreaIds = [];
    //已选城市ID
    var selCityIds = [];
    //已选地区名称
    var selAreaNames = [];

    var AreaModel = Backbone.Model.extend();
    var SelView = Backbone.View.extend({
        tagName:"li",
        template: _.template('<span data-id="<%= id %>"><%= name %></span><a href="javascript:void(0)" title="删除该区域" class="J_MultiDel"></a>'),
        events:{
            "click .J_MultiDel":"deleteSel"
        },
        initialize:function(){
            var _this = this;
            _.bindAll(this,"render");
            this.render();
        },
        render:function(){
            var data = this.model;
            this.$el.html(this.template(data));
            return this;
        },
        deleteSel:function(event){
            var $this = $(event.target),
                id = $this.siblings("span").attr("data-id"),
                name = $.trim($this.siblings("span").text()),
                $del = $this.parent("li"),
                $wrap = $this.parents(".J_MultiAreaSel"),
                $area = $wrap.find(".province-list"),
                $sel = $area.find("input[value="+id+"]"),
                isCity = $sel.parents("ul").hasClass("city-list");
            $del.remove();
            $sel.prop("checked",false);
            $sel.parent().parent().removeClass("selected");
            selAreaIds.splice($.inArray(id,selAreaIds),1);
            var selType = isCity ? "city" : (name == "北京" || name == "天津" || name == "上海" || name == "重庆" ? "cityProv" : "prov");
            switch(selType){
                case "city":
                    var unSelNum = $sel.parents(".city-list").find("input:not(:checked)").length,
                        sum = $sel.parents(".city-list").find("input:not(:checked)").length;
                    //删除元素为城市时,直接从城市列表中删除
                    selCityIds.splice($.inArray(id,selCityIds),1);
                    if(unSelNum>=sum){
                        $sel.parents(".city-list").parent("li").removeClass("selected");
                    }
                    break;
                case "cityProv":
                    selCityIds.splice($.inArray(id,selCityIds),1);
                    break;
                case "prov":
                    var $cities = $sel.parent("label").siblings("ul");
                    $cities.find("input").each(function(){
                        var id = $(this).val();
                        selCityIds.splice($.inArray(id,selCityIds),1);
                        $(this).prop("checked",false);
                        $(this).parent().parent("li").removeClass("selected");
                    });
            }
        }
    });
    var AreaView = Backbone.View.extend({
        tagName:"ul",
        className:"fn-clear",
        template: _.template('<% _.each( provs, function(p){ %><li><label><input type="checkbox" value="<%= p.id %>"><span><%=  p.name%></span><% if( !p.noChild ){ %><i></i><% } %></label><sub></sub><ul class="city-list fn-clear"><% _.each( p.cities,function(c){ %> <li class="J_C" ><label><input type="checkbox" value="<%= c.id %>"><span><%= c.name %></span></label></li> <% } ) %></ul></li></ul></li><% }) %>'),
        events:{
            "mouseover li:not(.J_C)":"showCity",
            "mouseout li:not(.J_C)":"hideCity",
            "change li:not(.J_C)>label>input":"changeProv",
            "change li.J_C>label>input":"changeCity",
            "change input":"checkChange"
        },
        initialize:function(options){
            var _this = this;
            this.model = new AreaModel();
            this.model.url = options.dataUrl;
            _.bindAll(this,"render");
            this.model.fetch({ success:_this.render });
        },
        render:function(){
            this.$el.html(this.template(this.model.toJSON()));
            var len = selAreaIds.length;
            if(len<=0){return this;}
            for( var i = 0; i < len; i++ ){
                var $sel = this.$("input[value="+selAreaIds[i]+"]");
                $sel.prop("checked",true);
                $sel.parents("li").addClass("selected");
            }
            for( var i = 0,max = selCityIds.length; i < max; i++ ){
                var $sel = this.$("input[value="+selCityIds[i]+"]");
                $sel.prop("checked",true);
                $sel.parents("li").addClass("selected");
            }
            return this;
        },
        showCity:function(event){
            var $this =$(event.currentTarget),width;
            if($this.find("i").length<=0) return;
            width = $this.width()+10;
            $this.children("sub").width(width);
            $this.addClass("current").siblings("li").removeClass("current");
        },
        hideCity:function(event){
            var $this = $(event.currentTarget);
            $this.removeClass("current");
        },
        selectSingle:function($this){
            var $wrap = $this.parents(".J_MultiAreaSel"),
                $selWrap = $wrap.find(".selected-area>ul")
            $wrap.find("input").prop("checked",false);
            $selWrap.find("li").remove();
            selAreaIds.splice($.inArray("0",selAreaIds),1);
            selCityIds.splice($.inArray("0",selAreaIds),1);
            $this.prop("checked",true);
            $wrap.find("li").removeClass("selected");
            $wrap.find(".province-list>p").removeClass("selected");
        },
        changeProv:function(event){
            var $this = $(event.currentTarget),
                provId = $this.val(),
                provName = $.trim($this.siblings("span").text()),
                $city = $this.parent("label").siblings(".city-list"),
                $wrap = $this.parents(".J_MultiAreaSel"),
                $selWrap = $wrap.find(".selected-area>ul"),
                selModel,selView;
            if($.inArray("0",selAreaIds)>=0){
                this.selectSingle($this)
            }
            if($this.prop("checked")){
                //从已选列表(selected-area)中添加当前省份
                selModel = { "id":provId, "name":provName };
                selView = new SelView({ model:selModel });
                $selWrap.append(selView.el);
                //将所选省份添加到已选区域数组中
                selAreaIds.push(provId);
                $this.parent().parent("li").addClass("selected")
                //全选子集城市
                $city.find("input").prop("checked",true);
                $city.find("li").addClass("selected");
                //处理子城市
                if(provName == "北京" || provName == "天津" || provName == "上海" || provName == "重庆" ){
                    selCityIds.push(provId);
                }else{
                    $city.find("input").each(function(){
                        var id = $(this).val(),
                            $del = $wrap.find(".selected-area span[data-id="+id+"]").parents("li");
                        //从已选区域中删除子集市Id
                        if($.inArray(id,selAreaIds)>=0){ selAreaIds.splice($.inArray(id,selAreaIds),1); }
                        //添加已选城市ID
                        if($.inArray(id,selCityIds)<0){ selCityIds.push(id); }
                        //从已选列表中(selected-area)删除子集城市
                        $del.remove();
                    });
                }
            }else{
                selAreaIds.splice($.inArray(provId,selAreaIds),1);
                $this.parent().parent("li").removeClass("selected")
                //全部子集城市取消选中状态
                $city.find("input").prop("checked",false);
                $city.find("li").removeClass("selected");
                var $del = $wrap.find(".selected-area span[data-id="+provId+"]").parents("li");
                $del.remove();
                if(provName == "北京" || provName == "天津" || provName == "上海" || provName == "重庆" ){
                    selCityIds.splice($.inArray(provId,selCityIds),1);
                }else{
                    //已选城市数组删除该省子城市ID
                    $city.find("input").each(function(){
                        var id = $(this).val();
                        selCityIds.splice($.inArray(id,selCityIds),1);
                    });
                }
            }
        },
        changeCity:function(event){
            var $this = $(event.target),
                id = $this.val(),
                name = $.trim($this.siblings("span").text()),
                $prov = $this.parents(".city-list").siblings("label"),
                provId = $prov.children("input").val(),
                provName = $.trim($prov.children("span").text()),
                $wrap = $this.parents(".J_MultiAreaSel"),
                $selWrap = $wrap.find(".selected-area>ul");
            if($.inArray("0",selAreaIds)>=0){
                this.selectSingle($this)
            }
            if($this.prop("checked")){
                var unSelNum = $this.parents(".city-list").find("input:not(:checked)").length,
                    selModel,selView;
                selCityIds.push(id);
                if(unSelNum<=0){
                    selModel = { "id":provId, "name":provName };
                    selView = new SelView({ model:selModel });
                    $this.parents(".city-list").find("input").each(function(){
                        var id = $(this).val(),
                            $delBlk = $wrap.find(".selected-area span[data-id="+id+"]").parents("li");
                        selAreaIds.splice($.inArray(id,selAreaIds),1);
                        $delBlk.remove();
                    });
                    selAreaIds.push(provId);
                    $prov.children("input").prop("checked",true);
                    $prov.parent("li").addClass("selected");
                }else{
                    selModel = { "id":id, "name":name };
                    selView = new SelView({ model:selModel });
                    selAreaIds.push(id);
                }
                $selWrap.append(selView.el);
                $this.parents("li").addClass("selected");
            }else{
                var $del,
                    unSelNum = $this.parents(".city-list").find("input:not(:checked)").length,
                    sum = $this.parents(".city-list").find("input").length;
                if(unSelNum<=1){
                    $prov.children("input").prop("checked",false);
                    $this.parents(".city-list").find("input:checked").each(function(){
                        var cid = $(this).val(),cname = $.trim($(this).siblings("span").text());
                        selModel = { "id":cid, "name":cname };
                        selView = new SelView({ model:selModel });
                        $selWrap.append(selView.el);
                        selAreaIds.push(cid);
                    });
                    $del = $wrap.find(".selected-area span[data-id="+provId+"]").parents("li");
                    selAreaIds.splice($.inArray(provId,selAreaIds),1);
                }else{
                    $del = $selWrap.find("span[data-id="+id+"]").parent('li');
                    selAreaIds.splice($.inArray(id,selAreaIds),1);
                }
                if(unSelNum>=sum){
                    $prov.parent("li").removeClass("selected");
                }
                $this.parent().parent("li").removeClass("selected");
                selCityIds.splice($.inArray(id,selCityIds),1);
                $del.remove();
            }
        }
    });
    var AppView = Backbone.View.extend({
        tagName:"div",
        template: _.template(areaTemp),
        events:{
            "click .J_MultiClose" : "close",
            "click .J_MultiSubmit":"submit",
            "click .J_MultiClear":"clear",
            "change .J_Nation input":"selectNation"
        },
        initialize:function(options){
            this.dataUrl = options.dataUrl;
            this.idField = options.areaIds;
            this.nameField = options.areaNames;
            this.cityField = options.cityIds;
            selAreaIds = $.trim(options.areaIds.val())=="" ? [] : $.trim(options.areaIds.val()).split(',');
            selAreaNames = $.trim(options.areaNames.val())=="" ? [] : $.trim(options.areaNames.val()).split(',');
            selCityIds = $.trim(options.cityIds.val())=="" ? [] : $.trim(options.cityIds.val()).split(',');
            _.bindAll(this,"render");
            this.render();
        },
        render:function(){
            var _this = this;
            var maskH = this.getWinHeight();
            this.$el.html(this.template());
            this.$(".J_MultiMask").height(maskH);
            $(window).resize(function(){
                this.$(".J_MultiMask").height(_this.getWinHeight());
            });
            //已选择
            if(selAreaIds.length > 0 && selAreaIds[0]!=""){
                for(var i = 0, len = selAreaIds.length; i<len; i++){
                    var selModel = {"id": selAreaIds[i], "name": selAreaNames[i]};
                    var selView = new SelView({ model:selModel });
                    _this.$(".selected-area>ul").append(selView.el);
                }
            }
            //所有省份
            var provView = new AreaView({dataUrl:_this.dataUrl});
            this.$(".province-list").append(provView.el);
            return this;
        },
        getWinHeight:function(){
            var screenH = $(window).height(),
                bodyH = $("body").height(),
                maskH = screenH>bodyH ? screenH : bodyH;
            return maskH;
        },
        close:function(){
            this.$el.remove();
        },
        submit:function(){
            selAreaNames=[];
            var $sels = this.$(".selected-area").find("li");
            $sels.each(function(){
                var name = $(this).find("span").text();
                name = $.trim(name);
                selAreaNames.push(name);
            });
            this.idField.val(selAreaIds);
            this.cityField.val(selCityIds);
            this.nameField.val(selAreaNames);
            this.close();
            this.cityField.trigger("change");
        },
        clear:function(){
            var $sel = this.$(".selected-area"),
                $list = this.$(".province-list");
            selAreaIds=[];
            selCityIds=[];
            $sel.find("li").remove();
            $list.find("input").prop("checked",false);
            $list.find("li").removeClass("selected");
        },
        selectNation:function(event){
            var $this = $(event.target),
                selModel, selView,
                $sel = this.$(".selected-area").find("ul"),
                $list = this.$(".province-list");
            if($this.prop("checked")){
                $sel.find("li").remove();
                selModel = {id:"0",name:"全国"};
                selView = new SelView({model:selModel});
                $sel.append(selView.el);
                selAreaIds=["0"];
                selCityIds=["0"];
                $list.find("input").prop("checked",true);
                $list.find("li").addClass("selected");
                $this.parents("p").addClass("selected");
            }else{
                this.clear();
                $this.parents("p").removeClass("selected");
            }
        }

    });
    module.exports = AppView;

});